﻿using UnityEngine;
using UnityEngine.UI;

namespace SG
{
    /*
     * 如果是图片，就会创建一个画布，给这个画布设定render层次，以起到渲染顺序的修改
     * 如果是粒子，就修改粒子下所有的render节点，来修改渲染顺序
     * 所有的order不能大于10，因为界面管理默认规则里，每个界面之间的渲染序列相差10，如果超过10，就会和上一层的渲染相同，遮挡顺序就错了
     */
    public class UISortingOrder : UISortingOrderBase
    {
        [Header("所在层的序列，如果挂在界面上，这个值是相对值，如果不是界面，就是绝对值，不能超过10")]
        [Range(0, 10)]
        public int m_Order = 0;
        [Header("如果是，会自动创建画布，用于特殊图片，,如果不是，应该是一个粒子特效")]
        public bool m_IsImage = false;
        Canvas m_canvas;

        public override void SetOrder(int order)
        {
            int curOrder = m_Order + order;
            if (m_IsImage)
            {
                if (m_Order < 10)
                    GetCanvas().sortingOrder = curOrder;
                GetCanvas().overrideSorting = true;
            }
            // 把下面所有的render进行排序
            Renderer[] renders = GetComponentsInChildren<Renderer>(true);
            foreach (Renderer render in renders)
            {

                render.sortingOrder = order + curOrder;
            }

        }
        /// <summary>
        /// From MonoBehaviour
        /// </summary>
        private void Start()
        {
            if (m_IsImage && m_Order > 10)
            {
                XKLog.Log("是ui上的层，而且超过10了，说明不是粒子效果，检查 [" + gameObject.name + "]" + "  = " + m_Order);
            }
        }
        Canvas GetCanvas()
        {
            Vector3 scale = Vector3.zero;
            Vector3 ps = Vector3.zero;
            if (m_canvas == null)
            {
                var rt = gameObject.GetComponent<RectTransform>();
                if (rt != null)
                {
                    scale = rt.localScale;
                    ps = rt.localPosition;
                }
                m_canvas = gameObject.GetOrAddComponent<Canvas>();
                m_canvas.renderMode = RenderMode.ScreenSpaceCamera;
                m_canvas.worldCamera = UIMgr.Instance().m_uiCamera2d;
                m_canvas.overrideSorting = true;
                // 如果有按钮，就需要吧射线检测开开
                if (gameObject.GetComponentInChildren<Button>() != null)
                {
                    gameObject.AddComponent<GraphicRaycaster>();
                }
                if (rt != null)
                {
                    rt.localScale = scale;
                    rt.localPosition = ps;
                }
            }
            return m_canvas;
        }
    }
}